package com.codeworker.asyncrequestresenddemo.manager;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * Description: 模拟第三方请求
 *
 * @author code-worker
 * @date 2021/10/14 20:01
 */
@Service("AsyncManager")
public class AsyncManager {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * task: 异步方法
     * @param num 数字
     * @author code-worker
     * @date 2021/10/14 20:13
     */
    @Async
    public void method01(int num){
        System.out.println("this is AsyncManager method01 thread: "+ Thread.currentThread().getName() + ", time: " + LocalTime.now());
        try {
            Thread.sleep(10000);
        }catch (InterruptedException e) {
            System.out.println("AsyncManager | method01 | InterruptedException" + e.getMessage());
        }
        method02(num);
    }

    /**
     * task: 内部私有方法
     * @param num 数字
     * @author code-worker
     * @date 2021/10/14 20:13
     */
    private void method02(int num){
        System.out.println("this is AsyncManager method02 thread: " + Thread.currentThread().getName() + ", time: " + LocalTime.now());
        if(Boolean.FALSE.equals(stringRedisTemplate.hasKey("data" + num)) ||
                Long.parseLong(Objects.requireNonNull(stringRedisTemplate.opsForValue().get("data" + num))) < 5){
            System.out.println("AsyncManager | method02 counter: " + stringRedisTemplate.opsForValue().get("data" + num) + ", time: " + LocalTime.now());
            stringRedisTemplate.opsForValue().increment("data" + num);
            method01(num);
        }
    }
}
